module Fluent
  class HawkOutput < BufferedOutput
    Plugin.register_output("hawk", self)

    # Define parameters for your plugin
    config_param :hawk_api, :string #The hawk sample host api

    def initialize
      super
      require 'net/http'
      require "base64"
      require 'json'
    end

    def configure(conf)
      super
    end

    def start
      super
    end

    def shutdown
      super
    end

    def format(tag, time, record)
      #log.debug record: record
      record.to_msgpack
    end

    def write(chunk)
      #log.debug "write()!"
      #real_path = extract_placeholders(@path, chunk)

      # File.open(@path, 'a+') do |file| 
      chunk.open { |io|
        begin
          MessagePack::Unpacker.new(io).each.each_with_index { |record, index|
            log.debug "iterator:", record: record, index: index
            send(record)
          }
          rescue EOFError
          # EOFError always occured when reached end of chunk. 
        end
      }
    end

    def send(data)
      uri = URI(@hawk_api)
      req = Net::HTTP::Post.new(uri) 
      str = JSON.generate(data)
      log.debug str:str
      base = Base64.encode64(str)
      log.debug base:base
      req.set_form_data('data' => base) 
 
      res = Net::HTTP.start(uri.hostname, uri.port) do |http|
        http.request(req)
      end
    end

  end
end	  